package com.jingtuo.android.common.widget;

import java.util.List;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

public class ViewPagerAdapter<T> extends PagerAdapter {

	protected List<T> data;
	
	protected FragmentManager mFragmentManager;
	protected FragmentTransaction mCurTransaction = null;
	protected Fragment mCurrentPrimaryItem = null;

	public ViewPagerAdapter(FragmentManager fm, List<T> data) {
		this.mFragmentManager = fm;
		this.data = data;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return data.size();
	}
	
	public Fragment getItem(int position) {
		return getItem(position);
	}

	public Object instantiateItem(ViewGroup container, int position) {
		if (this.mCurTransaction == null) {
			this.mCurTransaction = this.mFragmentManager.beginTransaction();
		}
		String name = createTagName(position);
		Fragment fragment = this.mFragmentManager.findFragmentByTag(name);
		if (fragment != null) {
			this.mCurTransaction.attach(fragment);
		} else {
			fragment = getItem(position);
			this.mCurTransaction.add(container.getId(), fragment,name);
		}
		if (fragment != this.mCurrentPrimaryItem) {
			fragment.setMenuVisibility(false);
			fragment.setUserVisibleHint(false);
		}
		return fragment;
	}

	public void destroyItem(ViewGroup container, int position, Object object) {
		if (this.mCurTransaction == null) {
			this.mCurTransaction = this.mFragmentManager.beginTransaction();
		}
		this.mCurTransaction.detach((Fragment) object);
	}

	public void setPrimaryItem(ViewGroup container, int position,
			Object object) {
		Fragment fragment = (Fragment) object;
		if (fragment != this.mCurrentPrimaryItem) {
			if (this.mCurrentPrimaryItem != null) {
				this.mCurrentPrimaryItem.setMenuVisibility(false);
				this.mCurrentPrimaryItem.setUserVisibleHint(false);
			}
			if (fragment != null) {
				fragment.setMenuVisibility(true);
				fragment.setUserVisibleHint(true);
			}
			this.mCurrentPrimaryItem = fragment;
		}
	}

	public void finishUpdate(ViewGroup container) {
		if (this.mCurTransaction != null) {
			this.mCurTransaction.commitAllowingStateLoss();
			this.mCurTransaction = null;
			this.mFragmentManager.executePendingTransactions();
		}
	}

	public boolean isViewFromObject(View view, Object object) {
		return ((Fragment) object).getView() == view;
	}

	public long getItemId(int position) {
		return position;
	}

	public String createTagName(int position){
		return getClass().getSimpleName() + "_" + position;
	}
	
}
